import datetime
from google.appengine.api.urlfetch import fetch, DownloadError
from google.appengine.ext import db

def get_rate(currency1, currency2, date=None):
    date_str = 'getlatest' if date is None else ('getrate/' + date.isoformat())
    url = 'http://currencies.apps.grandtrunk.net/%s/%s/%s'%(date_str, currency1, currency2)
    try:
        response = fetch(url)
        if response.status_code == 200:
            return float(response.content)
    except DownloadError:
        pass
    return None

class ExchangeRate(db.Model):
    date = db.DateProperty(required=True)
    currency1 = db.StringProperty(required=True)
    currency2 = db.StringProperty(required=True)
    rate = db.FloatProperty(required=True)
    
    @classmethod
    def latest(cls, currency1, currency2):
        c1, c2 = (currency1.lower(), currency2.lower())
        if c1 == c2: return 1.0
        today = datetime.date.today()
        key_name = '%s.%s.%s'%(today.isoformat(), c1, c2)
        exchange_rate = cls.get_by_key_name(key_name)
        if exchange_rate is not None:
            return exchange_rate.rate
        else:
            rate = get_rate(c1, c2, today)
            if rate is not None:
                ExchangeRate(key_name=key_name, date=today, currency1=c1, currency2=c2, rate=rate).put()
                key_name_rev = '%s.%s.%s'%(today.isoformat(), c2, c1)
                ExchangeRate(key_name=key_name_rev, date=today, currency1=c2, currency2=c1, rate=1./rate).put()
            else:
                q = ExchangeRate.all().filter('currency1 == ', c1).filter('currency2 == ', c2).order('-date').fetch(1)
                rate = q[0].rate if q else 0.
            return rate

def convert(amount, from_currency, to_currency):
    rate = ExchangeRate.latest(to_currency, from_currency)
    return amount / rate

def add(amount_list, to_currency):
    return sum([convert(a, c, to_currency) for (a, c) in amount_list])